<template>
  <div class="app-container">
    <!-- header -->
    <div class="filterContainer">
      <el-select v-model="institute_id" placeholder="请选择学院" clearable @change="changeI">
        <el-option v-for="item in options" :key="item.institute_id" :label="item.institute_name"
          :value="item.institute_id">
        </el-option>
      </el-select>
      <el-select v-model="grade_id" placeholder="请选择年级" clearable>
        <el-option v-for="item in Goptions" :key="item.grade_id" :label="item.grade_name" :value="item.grade_id">
        </el-option>
      </el-select>
      <el-input v-model="keyword" placeholder="关键字" style="width: 200px; margin-right: 10px" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <!-- 表格 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="课程图片" width="180">
        <template slot-scope="scope">
          <el-popover placement="top-start" width="300" trigger="hover">
            <div style="display: flex;flex-direction: column;">
              <span>
                报名开始时间: {{ scope.row.apply_start_date }}
              </span>
              <span>
                报名截止时间: {{ scope.row.apply_end_date }}
              </span>
              <span>
                开课时间: {{ scope.row.start_date }}
              </span>
              <span>
                结课时间: {{ scope.row.end_date }}
              </span>
            </div>
            <div slot="reference"
              style="width: 120px;height: 60px;display: flex;justify-content: center;align-items: center;margin: 0 auto;overflow: hidden;background-color: #ccc;">
              <i v-if="!scope.row.course_image" class="el-icon-picture-outline"></i>
              <el-image v-else style="height: 80px;" fit="contain"
                :src="'http://localhost:3001/image/courseimg/' + scope.row.course_image"></el-image>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="学院名称" width="120" align="center">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="学院" width="200" trigger="hover" :content="scope.row.institute_name">
            <span slot="reference" style="width: 100px;;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
              {{ scope.row.institute_name }}
            </span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="年级名称" width="120" align="center">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="年级" width="200" trigger="hover" :content="scope.row.grade_name">
            <span slot="reference" style="width: 100px;;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
              {{ scope.row.grade_name }}
            </span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="教师姓名" width="120" align="center">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="老师姓名" width="200" trigger="hover" :content="scope.row.teacher_name">
            <span slot="reference" style="width: 100px;;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
              {{ scope.row.teacher_name }}
            </span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="课程名称" width="120" align="center">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="课程名称" width="200" trigger="hover" :content="scope.row.course_name">
            <span slot="reference" style="width: 100px;;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
              {{ scope.row.course_name }}
            </span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="学分" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.course_credit }}
        </template>
      </el-table-column>
      <el-table-column label="课程人数" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.course_num }}
        </template>
      </el-table-column>
      <el-table-column label="课程简介" align="center">
        <template slot-scope="scope">
          <el-popover v-if="scope.row.course_desc == ''" placement="top-start" title="课程简介" width="200" trigger="hover"
            content="该老师很懒，还没更新课程简介!">
            <span slot="reference" style="width: 100px;;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
              null
            </span>
          </el-popover>
          <el-popover v-else placement="top-start" title="课程简介" width="200" trigger="hover"
            :content="scope.row.course_desc">
            <span slot="reference" style="width: 100px;;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
              {{ scope.row.course_desc }}
            </span>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="200">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row, $index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑年级信息弹框 -->
    <el-dialog title="课程信息" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="dialogform">
        <el-form-item class="upload" label="课程图片：" v-if="dialogStatus == 'create'">
          <div style="
                display: flex;
                justify-content: center;
                align-items: center;
              ">
            <div v-show="!fileContent"
              style="width: 130px;height: 70px;display: flex;justify-content: center;align-items: center;margin: 0 auto;overflow: hidden;background-color: #ccc;margin-right: 40px;">
              <i v-if="!form.course_image" class="el-icon-picture-outline"></i>
              <el-image v-else style="width: 150px;" fit="contain"
                :src="'http://localhost:3001/image/courseimg/' + form.course_image"></el-image>
            </div>
            <div v-show="fileContent"
              style="width: 130px;height: 70px;display: flex;justify-content: center;align-items: center;margin: 0 auto;overflow: hidden;background-color: #ccc;margin-right: 40px;">
              <el-image style="width: 150px;" fit="contain" :src="fileContent"></el-image>
            </div>

            <!-- <input type="file" id="image" @change="selectImg" style="display: none" /> -->
            <el-button @click="show" id="btn" style="display: none;"></el-button>
            <!-- <label for="image"> -->
            <label for="btn">
              <div style="
                    width: 100px;
                    height: 35px;
                    backgroundColor: #409eff;
                    cursor: pointer;
                    color: #fff;
                    border-radius: 5px;
                    text-align: center;
                    line-height: 35px;
                    font-weight: 500
                  ">
                点击上传
              </div>
            </label>
          </div>
        </el-form-item>

        <el-form-item v-if="dialogStatus == 'create'" label="学院名称" prop="institute_id">
          <el-select v-model="form.institute_id" placeholder="please select institute" clearable @change="changeI">
            <el-option v-for=" item  in  options " :key="item.institute_id" :label="item.institute_name"
              :value="item.institute_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="dialogStatus == 'create'" label="年级名称" prop="grade_id">
          <el-select v-model="form.grade_id" placeholder="please select grade" clearable>
            <el-option v-for=" item  in  Goptions " :key="item.grade_id" :label="item.grade_name" :value="item.grade_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="老师名称" prop="teacher_id">
          <el-select v-model="form.teacher_id" placeholder="please select teacher" clearable>
            <el-option v-for=" item  in  Toptions " :key="item.teacher_id" :label="item.teacher_name"
              :value="item.teacher_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="报名时间">
          <el-date-picker v-model="applydate" type="datetimerange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="课程时间">
          <el-date-picker v-model="date" type="datetimerange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="课程名称" prop="course_name">
          <el-input v-model="form.course_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学分" prop="course_credit">
          <el-input v-model="form.course_credit" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="成员人数" prop="course_num">
          <el-input v-model="form.course_num" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程简介" prop="course_desc">
          <el-input v-model="form.course_desc" autocomplete="off" type="textarea" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
          @click="dialogStatus === 'create' ? createData('dialogform') : confirmedit('dialogform')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 图片裁剪弹框 -->
    <Cropper :dialogCropper="dialogCropper" :imgUrl="nowImage" :fixedNumber="[16, 9]" :loading="loading"
      @closeDialog="dialogCropper = false" @blobData="handleBlobData" v-if="nowImage">
    </Cropper>
    <!-- 分页 -->
    <div>
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
        @pagination="fetchData" />
    </div>
  </div>
</template>

<script>
import {
  getInstitute,
  searchGrade,
  searchTeacher,
  getCourse,
  searchCourse,
  addCourse,
  deleteCourse,
  editCourse,
} from '@/api/infotable'
import Pagination from "@/components/Pagination";
// import * as imageConversion from 'image-conversion';
import Cropper from "@/components/Cropper/Cropper";

export default {
  components: {
    Pagination,
    Cropper
  },
  filters: {

  },
  data() {
    return {
      // 列表
      list: null,
      // 加载
      listLoading: true,
      // 搜索
      options: null,
      institute_id: '',
      Goptions: null,
      grade_id: '',
      Toptions: null,
      teacher_id: '',
      keyword: '',
      // 分页
      total: 1,
      // 传递的页号
      listQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      // 弹框
      dialogFormVisible: false,
      form: {
        institute_id: '',
        grade_id: '',
        teacher_id: '',
        course_name: '',
        course_credit: '',
        course_desc: '',
        course_num: '',
        course_image: '',
      },
      // 中间量
      obj: null,
      // 状态
      dialogStatus: "",
      rules: {
        institute_id: [
          { required: true, message: '学院不能为空', trigger: 'blur' }
        ],
        grade_id: [
          { required: true, message: '年级不能为空', trigger: 'blur' }
        ],
        teacher_id: [
          { required: true, message: '老师不能为空', trigger: 'blur' }
        ],
        course_name: [
          { required: true, message: '课程不能为空', trigger: 'blur' }
        ],
        course_credit: [
          { required: true, message: '学分不能为空', trigger: 'blur' }
        ],
        course_num: [
          { required: true, message: '课程成员人数不能为空', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '课程时间不能为空', trigger: 'blur' }
        ],
        applydate: [
          { required: true, message: '报名时间不能为空', trigger: 'blur' }
        ],
      },
      fileContent: '',
      fileData: "",
      date: [],
      applydate: [],
      // 裁剪组件的基础配置option
      nowImage: '',
      dialogCropper: false,
      loading: false,
      squareUrl:
        'https://pic1.zhimg.com/80/v2-366c0aeae2b4050fa2fcbfc09c74aad4_720w.jpg',
    }
  },
  created() {
    this.fetchData()
    this.fetchInstiData()
    this.fetchGrade()
    this.fetchTeacher()
  },
  methods: {
    // 将标准时间转换为YYYY-MM-DD HH:MM:SS类型的
    formTime(time) {
      let newtime = new Date(time);
      // console.log(new Date(time), "要进行转换的时间");
      const year = newtime.getFullYear();
      const month = String(newtime.getMonth() + 1).padStart(2, "0");
      const day = String(newtime.getDate()).padStart(2, "0");
      const hours = String(newtime.getHours()).padStart(2, "0");
      const minutes = String(newtime.getMinutes()).padStart(2, "0");
      const seconds = String(newtime.getSeconds()).padStart(2, "0");

      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedDate;
    },
    // 获取信息
    fetchData() {
      this.listLoading = true
      getCourse(this.listQuery).then(response => {
        console.log(response);
        this.list = response.data.items.map(item => {
          return { ...item, apply_start_date: this.formTime(item.apply_start_date), apply_end_date: this.formTime(item.apply_end_date), start_date: this.formTime(item.start_date), end_date: this.formTime(item.end_date) }
        })
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 下拉--获取学院
    fetchInstiData() {
      this.listLoading = true
      getInstitute(this.listQuery).then((response) => {
        this.options = response.data.InList
        // this.options = response.data.InList.map(item => {
        //   return { ...item, grades: response.data.GrList.filter(g => g.institute_id == item.institute_id) }
        // })
        console.log(this.options);
        console.log(response.data);
        this.listLoading = false;
      });
    },
    // 根据学院筛选年级
    changeI(val) {
      console.log(val);
      searchGrade(this.listQuery, { institute_id: val, keyword: '' }).then((response) => {
        this.Goptions = response.data.items
        console.log(response.data);
      });
      searchTeacher(this.listQuery, { institute_id: val }).then((response) => {
        this.Toptions = response.data.items
        console.log(response.data);
      });
    },
    // 下拉--获取年级
    fetchGrade() {
      this.listLoading = true
      searchGrade(this.listQuery, { institute_id: this.form.institute_id, keyword: '' }).then((response) => {
        this.Goptions = response.data.items
        console.log(response.data);
        this.listLoading = false;
      });
    },
    // 下拉--获取老师
    fetchTeacher() {
      this.listLoading = true
      searchTeacher(this.listQuery, { institute_id: this.form.institute_id }).then((response) => {
        this.Toptions = response.data.items
        console.log(response.data);
        this.listLoading = false;
      });
    },
    // 将内容进行重置
    reset() {
      this.form.institute_id = ''
      this.form.grade_id = ''
      this.form.teacher_id = ''
      this.form.course_name = ''
      this.form.course_credit = ''
      this.form.course_desc = ''
      this.form.course_num = ''
      this.form.course_image = ''
      this.date = []
      this.applydate = []
    },
    // 添加课程
    handleCreate() {
      this.reset()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 添加课程
    createData(form) {
      console.log(this.form);
      console.log(this.Toptions.filter(obj => obj.teacher_id == this.form.teacher_id)[0].user_id);
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          addCourse({ ...this.form, apply_start_date: this.formTime(this.applydate[0]), apply_end_date: this.formTime(this.applydate[1]), start_date: this.formTime(this.date[0]), end_date: this.formTime(this.date[1]), recipient: this.Toptions.filter(obj => obj.teacher_id == this.form.teacher_id)[0].user_id })
            .then((response) => {
              console.log(response);
              if (response.code == 200) {
                this.fetchData()
                this.dialogFormVisible = false
              }
            })
        } else {
          this.$message.error('添加失败：存在未填项')
          return false;
        }
      });
    },
    // 搜索
    handleFilter() {
      this.listLoading = true
      searchCourse(this.listQuery, { keyword: this.keyword, institute_id: this.institute_id, grade_id: this.grade_id })
        .then((response) => {
          console.log(response);
          this.list = response.data.items.map(item => {
            return { ...item, apply_start_date: this.formTime(item.apply_start_date), apply_end_date: this.formTime(item.apply_end_date), start_date: this.formTime(item.start_date), end_date: this.formTime(item.end_date) }
          })
          this.total = response.data.total;
          this.listLoading = false;
        })
    },
    // 编辑
    handleUpdate(row) {
      console.log(row);
      this.dialogStatus = 'edit'
      this.fileContent = ''
      this.form.institute_id = row.institute_id
      this.form.grade_id = row.grade_id
      this.form.teacher_id = row.teacher_id
      this.form.course_name = row.course_name
      this.form.course_credit = row.course_credit
      this.form.course_desc = row.course_desc
      this.form.course_num = row.course_num
      this.form.course_image = row.course_image
      this.date = [new Date(row.start_date), new Date(row.end_date)]
      this.applydate = [new Date(row.apply_start_date), new Date(row.apply_end_date)]
      this.fileData = ''
      this.obj = row
      this.dialogFormVisible = true
      this.fetchTeacher()
    },
    // 编辑确定
    confirmedit(form) {
      console.log(this.Toptions);
      console.log(this.form);
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          if (this.obj.teacher_id == this.form.teacher_id && this.obj.course_credit == this.form.course_credit && this.obj.course_num == this.form.course_num && this.obj.course_desc == this.form.course_desc && this.fileData == '' && this.formTime(this.applydate[0]) == this.obj.apply_start_date && this.formTime(this.applydate[1]) == this.obj.apply_end_date && this.formTime(this.date[0]) == this.obj.start_date && this.formTime(this.date[1]) == this.obj.end_date) {
            this.fetchData()
            this.dialogFormVisible = false
          } else {
            editCourse({ ...this.form, course_id: this.obj.course_id, apply_start_date: this.formTime(this.applydate[0]), apply_end_date: this.formTime(this.applydate[1]), start_date: this.formTime(this.date[0]), end_date: this.formTime(this.date[1]), recipient0: this.Toptions.filter(item => item.teacher_id == this.obj.teacher_id)[0].user_id, recipient1: this.Toptions.filter(item => item.teacher_id == this.form.teacher_id)[0].user_id }, this.fileData)
              .then((response) => {
                console.log(response);
                if (response.code == 200) {
                  this.fetchData()
                  this.dialogFormVisible = false
                  this.loading = false
                }
              })
          }
        } else {
          this.$message.error('修改失败：不能为空')
          return false;
        }
      });
    },
    // 删除
    handleDelete(row) {
      console.log(row);
      this.$confirm('此操作将永久删除该课程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        deleteCourse({ course_id: row.course_id })
          .then((response) => {
            console.log(response);
            if (response.code == 200) {
              this.fetchData()
            }
          })
      });
    },
    show() {
      console.log(this.form.course_image);
      if (this.form.course_image) {
        this.nowImage = 'http://localhost:3001/image/courseimg/' + this.form.course_image
      } else {
        this.nowImage = this.squareUrl
      }
      console.log(this.nowImage);
      this.dialogCropper = true
    },
    // 裁剪图片后返回的blob
    async handleBlobData(blob) {
      // 处理 Blob 对象
      console.log(blob);
      const reader = new FileReader();
      reader.onload = () => {
        this.fileContent = reader.result;
      };
      reader.readAsDataURL(blob);
      let fd = new FormData()
      fd.append('courseImg', blob)
      this.fileData = fd;
      console.log(this.fileData);
    },
    // 选择图片
    // async selectImg(e) {
    //   const file = e.target.files[0];
    //   const reader = new FileReader();
    //   reader.onload = () => {
    //     this.fileContent = reader.result;
    //   };
    //   reader.readAsDataURL(file);
    //   let fd = new FormData();
    //   let fileList = e.target.files;
    //   console.log(123456)
    //   let obj = await this.ReadData(fileList[0]);
    //   console.log(obj)
    //   fd.append("courseImg", obj);
    //   this.fileData = fd;
    //   console.log(fd.get("courseImg"))
    // },
    // 图片压缩
    // ReadData(file) {
    //   console.log(file);
    //   const isJpgOrPng =
    //     file.type === "image/jpeg" || file.type === "image/png" || file.type === 'image/webp';
    //   const isSize = file.size / 1024 < 64;
    //   console.log(isSize);
    //   if (!isJpgOrPng) {
    //     this.$message.error("上传图片格式不符!");
    //     return false;
    //   }
    //   return new Promise((resolve, rej) => {
    //     // 小于64kb 不压缩
    //     if (isSize) {
    //       resolve(file);
    //     } else {
    //       console.log("需要进行压缩");
    //       // 压缩到64KB,这里的64就是要压缩的大小,可自定义
    //       imageConversion.compressAccurately(file, 64).then((res) => {
    //         console.log(res);
    //         resolve(new window.File([res], file.name, { type: file.type }));
    //       });
    //     }
    //   });
    // },
  },
  mounted() {
    // distributionGroup({id: "7065247328843595776"}).then(response => {
    //   console.log(response);
    // })
  }
}
</script>
<style scoped>
.filterContainer {
  margin-bottom: 30px;
}

.upload {
  display: flex;
}
</style>
